import React, { useState, useRef, useEffect } from 'react';
import { Upload, Button, message, Progress, Spin } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import type { UploadFile, UploadProps } from 'antd/es/upload/interface';
import { ImageUploader, ImageUploadResult } from '@/utils/ImageUploader';
import styles from './index.module.less';

// 假设这是从环境变量或配置中获取的
const REGION = 'cn-beijing';
const ENDPOINT = 'tos-cn-beijing.volces.com';
const BUCKET = 'your-bucket-name';
const BASE_URL = 'https://your-bucket-domain.com';

// 假设这是从后端获取STS临时凭证的API
const fetchSTSToken = async () => {
  try {
    const response = await fetch('/api/sts-token');
    if (!response.ok) {
      throw new Error('获取STS Token失败');
    }
    return await response.json();
  } catch (error) {
    console.error('获取STS Token失败:', error);
    throw error;
  }
};

interface ImageUploadProps {
  /** 文件列表 */
  value?: UploadFile[];
  /** 值变化回调 */
  onChange?: (fileList: UploadFile[]) => void;
  /** 上传目录 */
  directory?: string;
  /** 是否多选 */
  multiple?: boolean;
  /** 最大上传数量 */
  maxCount?: number;
  /** 接受的文件类型 */
  accept?: string;
  /** 按钮文本 */
  buttonText?: string;
  /** 按钮图标 */
  buttonIcon?: React.ReactNode;
  /** 是否禁用 */
  disabled?: boolean;
}

/**
 * 图片上传组件
 */
const ImageUpload: React.FC<ImageUploadProps> = ({
  value,
  onChange,
  directory = 'images',
  multiple = false,
  maxCount = 1,
  accept = 'image/*',
  buttonText = '上传图片',
  buttonIcon = <UploadOutlined />,
  disabled = false,
}) => {
  // 上传器实例
  const uploaderRef = useRef<ImageUploader | null>(null);
  // 初始化状态
  const [initializing, setInitializing] = useState(false);
  // 上传中的文件列表
  const [uploadingFiles, setUploadingFiles] = useState<Record<string, number>>({});

  // 初始化上传器
  const initializeUploader = async () => {
    if (uploaderRef.current) return true;

    try {
      setInitializing(true);
      // 创建上传器实例
      const uploader = new ImageUploader(REGION, ENDPOINT, BUCKET, BASE_URL);
      // 获取STS临时凭证
      const stsToken = await fetchSTSToken();
      // 初始化上传器
      const success = await uploader.initialize(stsToken);
      
      if (success) {
        uploaderRef.current = uploader;
        return true;
      }
      return false;
    } catch (error) {
      console.error('初始化上传器失败:', error);
      message.error('初始化上传器失败，请刷新页面重试');
      return false;
    } finally {
      setInitializing(false);
    }
  };

  // 处理文件上传
  const handleUpload = async (file: File): Promise<ImageUploadResult> => {
    // 确保上传器已初始化
    const initialized = await initializeUploader();
    if (!initialized) {
      return { success: false, error: '上传器初始化失败' };
    }

    // 生成唯一的文件ID用于跟踪上传进度
    const fileId = `${file.name}_${Date.now()}`;
    // 初始化进度为0
    setUploadingFiles((prev) => ({ ...prev, [fileId]: 0 }));

    try {
      // 上传图片
      const result = await uploaderRef.current!.uploadImage(file, {
        directory,
        onProgress: (percent) => {
          setUploadingFiles((prev) => ({ ...prev, [fileId]: percent }));
        },
      });

      // 上传完成后移除进度记录
      setUploadingFiles((prev) => {
        const newState = { ...prev };
        delete newState[fileId];
        return newState;
      });

      return result;
    } catch (error) {
      console.error('上传图片失败:', error);
      // 上传失败后移除进度记录
      setUploadingFiles((prev) => {
        const newState = { ...prev };
        delete newState[fileId];
        return newState;
      });
      return { success: false, error: error instanceof Error ? error.message : '上传失败' };
    }
  };

  // 自定义上传方法
  const customUpload: UploadProps['customRequest'] = async (options) => {
    const { file, onSuccess, onError } = options;
    
    if (!(file instanceof File)) {
      onError?.(new Error('上传文件类型错误'));
      return;
    }

    try {
      const result = await handleUpload(file);
      
      if (result.success && result.url) {
        // 上传成功
        onSuccess?.(result, new XMLHttpRequest());
      } else {
        // 上传失败
        onError?.(new Error(result.error || '上传失败'));
      }
    } catch (error) {
      onError?.(error instanceof Error ? error : new Error('上传失败'));
    }
  };

  // 处理文件列表变化
  const handleChange: UploadProps['onChange'] = ({ fileList }) => {
    // 过滤掉上传失败的文件
    const filteredFileList = fileList.filter((file) => file.status !== 'error');
    onChange?.(filteredFileList);
  };

  // 处理文件上传前的检查
  const beforeUpload: UploadProps['beforeUpload'] = (file) => {
    // 检查文件类型
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
      message.error('只能上传图片文件!');
      return false;
    }
    
    // 检查文件大小，限制为10MB
    const isLt10M = file.size / 1024 / 1024 < 10;
    if (!isLt10M) {
      message.error('图片大小不能超过10MB!');
      return false;
    }
    
    return true;
  };

  // 格式化文件列表，确保URL正确
  const formatFileList = (fileList?: UploadFile[]) => {
    if (!fileList) return [];
    
    return fileList.map(file => {
      // 如果URL不是完整的URL，则添加BASE_URL前缀
      if (file.url && !file.url.startsWith('http')) {
        return {
          ...file,
          url: `${BASE_URL}/${file.url.replace(/^\//, '')}`
        };
      }
      return file;
    });
  };

  // 初始化时格式化文件列表
  useEffect(() => {
    if (value) {
      const formattedFileList = formatFileList(value);
      if (JSON.stringify(formattedFileList) !== JSON.stringify(value)) {
        onChange?.(formattedFileList);
      }
    }
  }, []);

  return (
    <div className={styles.imageUpload}>
      <Spin spinning={initializing} tip="初始化上传器...">
        <Upload
          listType="picture-card"
          fileList={value}
          onChange={handleChange}
          customRequest={customUpload}
          beforeUpload={beforeUpload}
          multiple={multiple}
          maxCount={maxCount}
          accept={accept}
          disabled={disabled || initializing}
          showUploadList={{
            showPreviewIcon: true,
            showRemoveIcon: !disabled,
            showDownloadIcon: false,
          }}
        >
          {(!value || value.length < maxCount) && (
            <Button 
              icon={buttonIcon} 
              disabled={disabled || initializing}
            >
              {buttonText}
            </Button>
          )}
        </Upload>
        
        {/* 上传进度显示 */}
        {Object.entries(uploadingFiles).map(([fileId, percent]) => (
          <div key={fileId} className={styles.progressItem}>
            <div className={styles.fileName}>
              {fileId.split('_')[0]}
            </div>
            <Progress percent={Math.floor(percent)} size="small" />
          </div>
        ))}
      </Spin>
    </div>
  );
};

export default ImageUpload;